package com.nature.ffmpegforandroid

import android.Manifest
import android.opengl.GLSurfaceView
import android.os.Build
import android.os.Environment
import android.util.Log
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.core.app.ActivityCompat
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

/**
 *User: RandBII
 *Date: 2021/1/4
 *Description:
 */
class GLMediaPlayerActivity : BaseActivity(), GLSurfaceView.Renderer,
    NatureMediaPlayer.EventCallback, MyGLSurfaceView.MyOnGestureCallback {

    val REQUEST_CODE_PERMISSION = 0X002
    val NEED_PERMISSIONS =
        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)
    var natureMediaPlayer: NatureMediaPlayer? = null
    var mGLSurfaceView: MyGLSurfaceView? = null
    var mSeekBar: AppCompatSeekBar? = null
    var isTouch = false
    val videoPath = "${Environment.getExternalStorageDirectory().absolutePath}/zmg.mp4"


    override fun getResourceId() = R.layout.activity_gl_media


    override fun initViews() {
        mGLSurfaceView = findViewById(R.id.my_gl_surface_view)
        mSeekBar = findViewById(R.id.seek_bar)

        mGLSurfaceView?.let {
            it.setEGLContextClientVersion(3)
            it.setRenderer(this)
            it.mOnGestureCallback = this
            it.renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
        }


        mSeekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {


            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isTouch = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                natureMediaPlayer?.let {
                    it.seekToPosition(seekBar?.progress?.toFloat() ?: 0F)
                    isTouch = false
                }
            }
        })

        natureMediaPlayer = NatureMediaPlayer()
        natureMediaPlayer?.mEventCallback = this
        natureMediaPlayer?.natureMediaPlayerInit(
            videoPath,
            NatureMediaPlayer.VIDEO_RENDER_OPENGL,
            null
        )
    }

    override fun initDatas() {

    }

    override fun onResume() {
        super.onResume()
        if (hasPermissions(NEED_PERMISSIONS)) {
            natureMediaPlayer?.play()
        } else {
            ActivityCompat.requestPermissions(this, NEED_PERMISSIONS, REQUEST_CODE_PERMISSION)
        }

    }

    override fun onPause() {
        super.onPause()
        natureMediaPlayer?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        natureMediaPlayer?.unInit()
    }


    override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
        natureMediaPlayer?.native_onsurface_created(NatureMediaPlayer.VIDEO_GL_RENDER)
    }

    override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
        natureMediaPlayer?.native_onsurface_onchanged(
            NatureMediaPlayer.VIDEO_GL_RENDER,
            width,
            height
        )
    }

    override fun onDrawFrame(gl: GL10?) {
        natureMediaPlayer?.native_ondraw_frame(NatureMediaPlayer.VIDEO_GL_RENDER)
    }

    override fun onPlayerEvent(msgType: Int, msgValue: Float) {
        when (msgType) {
            NatureMediaPlayer.MSG_DECODER_READY -> {
                onDecoderReady()
            }
            NatureMediaPlayer.MSG_REQUEST_RENDER -> {
                mGLSurfaceView?.requestRender()
            }
            NatureMediaPlayer.MSG_DECODING_TIME -> {
                if (isTouch) mSeekBar?.progress = msgValue.toInt()
            }
            else -> {
                Log.e("GLMediaPlayer-->", "onPlayerEvent  msgTyp =$msgType ")
            }

        }
    }

    private fun onDecoderReady() {
        val videoWidth =
            natureMediaPlayer?.getMediaParams(NatureMediaPlayer.MEDIA_PARAM_VIDEO_WIDTH) ?: 0
        val videoHeight =
            natureMediaPlayer?.getMediaParams(NatureMediaPlayer.MEDIA_PARAM_VIDEO_HEIGHT) ?: 0

        if (videoHeight * videoWidth != 0L) mGLSurfaceView?.setAspectRatio(
            videoWidth.toInt(),
            videoHeight.toInt()
        )
        val duration =
            natureMediaPlayer?.getMediaParams(NatureMediaPlayer.MEDIA_PARAM_VIDEO_DURATION) ?: 0

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            mSeekBar?.min = 0
        }
        mSeekBar?.max = duration.toInt()
    }

    override fun onGesture(xRotateAngle: Int, yRotateAngle: Int, scale: Float) {
        NatureMediaPlayer.native_set_gesture(
            NatureMediaPlayer.VIDEO_GL_RENDER,
            xRotateAngle.toFloat(),
            yRotateAngle.toFloat(),
            scale.toInt()
        )

    }

    override fun onTouchLoc(touchX: Float, touchY: Float) {
        NatureMediaPlayer.native_set_touchloc(NatureMediaPlayer.VIDEO_GL_RENDER, touchX, touchY)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (!hasPermissions(NEED_PERMISSIONS)) {
                Toast.makeText(this, "请授予相应的权限", Toast.LENGTH_SHORT).show()
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }

    }


}